package com.fin.zw.intelligentbot.job;

import com.fin.zw.intelligentbot.entity.DialTask;
import com.fin.zw.intelligentbot.repository.DialTaskRepository;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

@Configuration
public class TaskServiceJob {

    private static Logger log = LoggerFactory.getLogger(TaskServiceJob.class);

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private DialTaskRepository dialTaskRepository;

    private static String dateFormat="ss mm HH dd MM ? yyyy";


    private String getCron(String taskId) {
        Optional<DialTask> optional = dialTaskRepository.findById(taskId);
        if(!optional.isPresent()){
            throw new RuntimeException("任务信息不存在！");
        }
        DialTask dialTask = optional.get();
        Date timing = dialTask.getTiming();
        String cron = formatDateByPattern(timing);
        log.info(cron);
        return cron;
    }

    public static String formatDateByPattern(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String formatTimeStr = null;
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

    public void start(String taskId)throws SchedulerException {
        startJob(scheduler,"auto_"+taskId,getCron(taskId),TaskJob.class);
    }

    private void startJob(Scheduler scheduler,String name,String cron,Class jobClass) throws SchedulerException {
        // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, "group1").build();
        // 基于表达式构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name, "group1")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * 获取Job信息
     * @param name
     * @param group
     * @return
     * @throws SchedulerException
     */
    public String getJobInfo(String name, String group) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 删除某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void deleteJob(String name, String group) throws SchedulerException {
        log.info("删除执行后的任务："+name);
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }
}
